package com.tgy.programmer_code_interview_guide._02_linkedList;

import com.tgy.leetcode.ListNode;

/**
 * @Author: tgy
 * @Date: 1/23/21 10:29 AM
 */
public class _05_链表部分翻转 {

    public static ListNode reverseBetween(ListNode head, int m, int n) {


        if (head == null || head.next == null || n == m) {

            return head;
        }

        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;
        ListNode begainNode = dummyNode, curNode = head;

        int index = 1;

        while (index < m && curNode != null) {

            begainNode = curNode;
            curNode = curNode.next;
            index++;
        }

        if (index != m) {

            return head;
        }

        ListNode preNode = null,nextNode = null;

        /**
         * index == n 时才进行 curNode.next 赋值，所以要加上=
         */
        while (index <= n && curNode != null) {

            nextNode = curNode.next;
            curNode.next = preNode;
            preNode = curNode;
            curNode = nextNode;
            index++;
        }

        begainNode.next.next = curNode;
        begainNode.next = preNode;

        return dummyNode.next;
    }

    public static void main(String[] args) {

        ListNode root = ListNode.general(new int[]{1, 2, 3, 4, 5, 6});
        ListNode reverseRoot = reverseBetween(root,1,3);
        ListNode.printListNode(reverseRoot);
    }
}
